//
//  SISSHouseCooperationDetailViewController.m
//  SISSAPP
//
//  Created by 优房网 on 2017/4/24.
//  Copyright © 2017年 优房网. All rights reserved.
//

#import "SISSHouseCooperationDetailViewController.h"
#import "SISSMorePopupView.h"
#import "SISSRequestCooperationView.h"
#import "SISSChatViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "SISSInfomationViewController.h"
#import "SISSNetworkingManager+Mine.h"
#import "SISSNetworkingManager+Home.h"
#import "SISSHouseResourceCooperationViewController.h"

@interface SISSHouseCooperationDetailViewController ()<SISSMorePopupViewDelegate,SISSRequestCooperationViewDelegate>

@property (weak, nonatomic) IBOutlet UILabel *neighbourhoodLabel;
@property (weak, nonatomic) IBOutlet UILabel *regionAndDetailLabel;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (weak, nonatomic) IBOutlet UILabel *houseTypeLabel;
@property (weak, nonatomic) IBOutlet UILabel *areaLabel;
@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *listTagLabels;
@property (weak, nonatomic) IBOutlet UILabel *propertyStateLabel;
@property (weak, nonatomic) IBOutlet UILabel *averagePriceLabel;
@property (weak, nonatomic) IBOutlet UILabel *directionLabel;
@property (weak, nonatomic) IBOutlet UILabel *buildYearLabel;
@property (weak, nonatomic) IBOutlet UILabel *decorationLabel;
@property (weak, nonatomic) IBOutlet UILabel *floorLabel;
@property (weak, nonatomic) IBOutlet UILabel *houseCodingLabel;
@property (weak, nonatomic) IBOutlet UILabel *houseDescriptionLabel;
@property (weak, nonatomic) IBOutlet UILabel *releaseTimeLabel;

@property (weak, nonatomic) IBOutlet UILabel *ownerPercentLabel;
@property (weak, nonatomic) IBOutlet UILabel *partnerPercentLabel;
@property (weak, nonatomic) IBOutlet UILabel *cooperationDescriptionLabel;

// 发布方信息
@property (weak, nonatomic) IBOutlet UIView *publisherView;
@property (weak, nonatomic) IBOutlet UIImageView *iconImageView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *companyNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *scoreLabel;
@property (weak, nonatomic) IBOutlet UIImageView *starLevelImageView;
@property (weak, nonatomic) IBOutlet UILabel *comment_countLabel;
@property (weak, nonatomic) IBOutlet UILabel *house_countLabel;
@property (weak, nonatomic) IBOutlet UILabel *passenger_countLabel;


@property (weak, nonatomic) IBOutlet UIView *consultAndRequestView;
@property (weak, nonatomic) IBOutlet UIView *onlineConsultButton;
@property (weak, nonatomic) IBOutlet UIView *requestCooperationButton;

@end

@implementation SISSHouseCooperationDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"房源合作详情";
    for (UILabel *label in self.listTagLabels) {
        
        label.hidden = YES;
    }
    
    // 判断是否显示发布方信息和咨询按钮
    self.publisherView.hidden = !self.isFindCooperation;
    self.consultAndRequestView.hidden = !self.isFindCooperation;
    self.consultAndRequestView.hidden = self.isHideConsultAndRequestView ?self.isHideConsultAndRequestView : !self.isFindCooperation;
    // 添加右侧分享删除按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"more..."] style:UIBarButtonItemStylePlain target:self action:@selector(shareAndComplainClick)];
    // 添加左侧的返回按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(backActon)];
}

- (void)backActon {
    
    if (self.isFindCooperation) {
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    
    for (UIViewController *controller in self.navigationController.viewControllers) {
        if ([controller isKindOfClass:[SISSHouseResourceCooperationViewController class]]) {
            [self.navigationController popToViewController:controller animated:YES];
        }
    }

}



- (void)setHouseCooperationModel:(SISSHouseCooperationDetailModel *)houseCooperationModel {
    
    [self.view layoutIfNeeded];
    _houseCooperationModel = houseCooperationModel;
    
    self.releaseTimeLabel.text = [houseCooperationModel.cooperation_insert_time substringToIndex:10];
    self.ownerPercentLabel.text = [NSString stringWithFormat:@"%zd%@",houseCooperationModel.commission_rate,@"%"];
    self.partnerPercentLabel.text = [NSString stringWithFormat:@"%zd%@",100 - houseCooperationModel.commission_rate,@"%"];
    self.cooperationDescriptionLabel.text = houseCooperationModel.cooperation_desc;
    
    if (!self.isFindCooperation) return;
    
    NSArray<UIColor *> *labelCololors = @[COLOR(0x33B189), COLOR(0xF76D81), COLOR(0x8E7FFF), COLOR(0x59ABFD), COLOR(0xE46B00)];
    
    for (int i = 0; i < houseCooperationModel.listTag.count; i++) {
        UILabel *label = self.listTagLabels[i];
        label.hidden = NO;
        label.layer.borderWidth = 1;
        label.text = [NSString stringWithFormat:@" %@ ",houseCooperationModel.listTag[i].tag];
        NSInteger colorIndex = houseCooperationModel.listTag[i].color - 1;
        label.layer.borderColor = labelCololors[colorIndex].CGColor;
        label.textColor = labelCololors[colorIndex];
        label.layer.cornerRadius = 2;
        label.layer.masksToBounds = YES;
    }
    
    self.neighbourhoodLabel.text = houseCooperationModel.neighbourhood;
    self.regionAndDetailLabel.text = [NSString stringWithFormat:@"%@-%@",houseCooperationModel.region,houseCooperationModel.regionDetail];
    self.priceLabel.text = [NSString stringWithFormat:@"%0.f万",houseCooperationModel.price];
    self.houseTypeLabel.text = houseCooperationModel.houseType;
    self.areaLabel.text = [NSString stringWithFormat:@"%0.f㎡",houseCooperationModel.area];
    self.propertyStateLabel.text = houseCooperationModel.propertyState;
    self.averagePriceLabel.text = [NSString stringWithFormat:@"%.0f元/㎡",houseCooperationModel.averagePrice * 10000];
    
    self.houseCodingLabel.text = houseCooperationModel.houseInfoNo;
    self.directionLabel.text = houseCooperationModel.direction.length ? houseCooperationModel.direction : @"暂无数据";
    self.buildYearLabel.text = houseCooperationModel.year ? [NSString stringWithFormat:@"%zd年",houseCooperationModel.year] : @"暂无数据";
    self.decorationLabel.text = houseCooperationModel.decoration.length ? houseCooperationModel.decoration : @"暂无数据";
    NSArray *floorsArr = @[@"1-10层", @"11-20层", @"21-30层", @"30层以上"];
    self.floorLabel.text = houseCooperationModel.floor ? floorsArr[houseCooperationModel.floor/11] : @"暂无数据";
    self.houseDescriptionLabel.text = houseCooperationModel.otherdesc.length ? houseCooperationModel.otherdesc : @"暂无数据";
    
    [self.iconImageView sd_setImageWithURL:[NSURL URLWithString:houseCooperationModel.portrait] placeholderImage:[UIImage imageNamed:@"头像"]];
    self.nameLabel.text = houseCooperationModel.name;
    self.scoreLabel.text = [NSString stringWithFormat:@"%zd",houseCooperationModel.score];
    self.comment_countLabel.text = [NSString stringWithFormat:@"共%zd人评价",houseCooperationModel.comment_count];
    self.starLevelImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"star_%zd",houseCooperationModel.star_level]];
    self.companyNameLabel.text = houseCooperationModel.shortName.length ? houseCooperationModel.shortName : houseCooperationModel.organName;
    self.house_countLabel.text = [NSString stringWithFormat:@"%zd",houseCooperationModel.house_count];
    self.passenger_countLabel.text = [NSString stringWithFormat:@"%zd",houseCooperationModel.demand_count];
    
}

- (void)setHouseResourceModel:(SISSHouseResourceModel *)houseResourceModel {
    
    [self.view layoutIfNeeded];
    _houseResourceModel = houseResourceModel;
    
    if (self.isFindCooperation) return;
    
    NSArray<UIColor *> *labelCololors = @[COLOR(0x33B189), COLOR(0xF76D81), COLOR(0x8E7FFF), COLOR(0x59ABFD), COLOR(0xE46B00)];
    
    for (int i = 0; i < houseResourceModel.listTag.count; i++) {
        UILabel *label = self.listTagLabels[i];
        label.hidden = NO;
        label.layer.borderWidth = 1;
        label.text = [NSString stringWithFormat:@" %@ ",houseResourceModel.listTag[i].tag];
        NSInteger colorIndex = houseResourceModel.listTag[i].color - 1;
        label.layer.borderColor = labelCololors[colorIndex].CGColor;
        label.textColor = labelCololors[colorIndex];
        label.layer.cornerRadius = 2;
        label.layer.masksToBounds = YES;
    }
    
    self.neighbourhoodLabel.text = houseResourceModel.neighbourhood;
    self.regionAndDetailLabel.text = [NSString stringWithFormat:@"%@-%@",houseResourceModel.region,houseResourceModel.regionDetail];
    self.priceLabel.text = [NSString stringWithFormat:@"%0.f万",[houseResourceModel.price floatValue]];
    self.houseTypeLabel.text = houseResourceModel.houseType;
    self.areaLabel.text = [NSString stringWithFormat:@"%@㎡",houseResourceModel.area];
    self.propertyStateLabel.text = houseResourceModel.propertyState;
    self.averagePriceLabel.text = [NSString stringWithFormat:@"%.0f元/㎡",[houseResourceModel.averagePrice floatValue] * 10000];
    self.directionLabel.text = houseResourceModel.direction.length ? houseResourceModel.direction : @"暂无数据";
    self.buildYearLabel.text = houseResourceModel.year ? [NSString stringWithFormat:@"%@年",houseResourceModel.year] : @"暂无数据";
    self.decorationLabel.text = houseResourceModel.decoration.length ? houseResourceModel.decoration : @"暂无数据";
    self.floorLabel.text = houseResourceModel.floor ? [NSString stringWithFormat:@"%zd层",houseResourceModel.floor] : @"暂无数据";
    self.houseCodingLabel.text = houseResourceModel.houseInfoNo;
    self.houseDescriptionLabel.text = houseResourceModel.otherdesc.length ? houseResourceModel.otherdesc : @"暂无数据";
    
}


/**
 分享投诉按钮事件
 */
- (void)shareAndComplainClick {
    
//    NSString *title = self.isFindCooperation ? @"举报" : @"删除";
    NSArray *titles = self.isFindCooperation ? @[@"分享", @"举报"] : @[@"分享"];
    SISSMorePopupView *moreView = [[SISSMorePopupView alloc] initWithTitles:titles];
    moreView.delegate = self;
    [moreView show];
}

#pragma mark - SISSMorePopupViewDelegate
- (void)morePopupViewSelectedWithIndex:(NSInteger)index {
    
    if (index == 0) {
        NSString *title = @"我有好房源，找客源合作。";
        NSString *descr = [NSString stringWithFormat:@"%@ | %@万\n%@-%@ | %@㎡ | %@",self.houseCooperationModel.neighbourhood, @(self.houseCooperationModel.price),self.houseCooperationModel.region,self.houseCooperationModel.regionDetail,@(self.houseCooperationModel.area),self.houseCooperationModel.houseType];
        NSString *webpageUrl = @"";
        if (self.houseResourceModel.houseresType == 1) { // 线上
            webpageUrl = [NSString stringWithFormat:@"%@/?#!/sellerHouseDetail/%@",WEB_BASE_URL,self.houseCooperationModel.ahrId];
        } else { // 线下
            webpageUrl = [NSString stringWithFormat:@"%@/#!/offlineHouseDetail/%@",WEB_BASE_URL,self.houseCooperationModel.ahrId];
        }
        
        [[SISSPublicSingleton shared] shareWithTitle:title descr:descr webpageUrl:webpageUrl currentViewController:self thumImage:self.houseCooperationModel.houseImage.firstObject];
    } else {
        
        SISSReportViewController *vc = [[SISSReportViewController alloc] init];
        SISSHouseResourceModel *houseModel = [[SISSHouseResourceModel alloc] init];
        houseModel.houseresType = self.houseCooperationModel.houseresType;
        houseModel.ID = self.houseCooperationModel.ahrId;
        vc.houseModel = houseModel;
        [self.navigationController pushViewController:vc animated:YES];
        if (self.isFindCooperation) { // 删除
            
            NSLog(@"=====删除");
//            [self deleteHouse];
            
        } else { // 举报
            
//            SISSReportViewController *vc = [[SISSReportViewController alloc] init];
//            
//            [self.navigationController pushViewController:vc animated:YES];
        }
        
    }
    
}


/**
 删除房源
 */
//- (void)deleteHouse {
//    
//    [kNetworkManager deleteHouseResourceWithHouseId:self.houseCooperationModel.ahrId successBlock:^(id responseObject) {
//        
//        if ([responseObject[@"code"] integerValue] == 200) { // 删除成功
//            
//            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
//[SISSTools showSVTitle:@"删除成功！" andTime:1.0 andColor:YES];
//}];
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                
////                if (self.deleteComplete) {
////                    self.deleteComplete();
////                }
//                [self.navigationController popViewControllerAnimated:YES];
//            });
//        }
//        
//    } failed:^(NSError *error) {
//        
//        NSLog(@"%@",error);
//    }];
//}

#pragma mark - 中介信息查询点击按钮
- (IBAction)checkInformationTapAction:(id)sender {
    
    [kNetworkManager requestPersonInfoWithSpId:self.houseCooperationModel.spId success:^(SISSPersonInfoModel *personInfo) {
        
        SISSInfomationViewController *vc = [[UIStoryboard storyboardWithName:@"Mine" bundle:nil] instantiateViewControllerWithIdentifier:@"SISSInfomationViewController"];
        vc.personInfo = personInfo;
        
        vc.spId = self.houseCooperationModel.spId;
        [self.navigationController pushViewController:vc animated:YES];
        
    } failed:^(NSError *error) {
        
        NSLog(@"%@",error);
    }];

}


/**
 在线咨询按钮点击事件
 */
- (IBAction)onlineConsultButtonClickAction:(id)sender {
    
    SISSChatViewController *chatVC = [[SISSChatViewController alloc] initWithConversationChatter:self.houseCooperationModel.imAccount conversationType:EMConversationTypeChat];
    SISSContactModel *model = [[SISSContactModel alloc] init];
    model.name = self.houseCooperationModel.name;
    model.portrait = self.houseCooperationModel.portrait;
    model.spId = self.houseCooperationModel.spId;
    model.accountType = 1;
    chatVC.contactModel = model;
    chatVC.title = self.houseCooperationModel.name;
    [self.navigationController pushViewController:chatVC animated:YES];
    NSLog(@"在线咨询按钮点击事件");
}


/**
 请求合作按钮点击事件
 */
- (IBAction)requestCooperationButtonCooperationClickAction:(id)sender {
    
    SISSRequestCooperationView *requestView = [[SISSRequestCooperationView alloc] init];
    requestView.delegate = self;
    requestView.cooperationTextStr = @"我对您发布的房源合作很感兴趣想和您进一步沟通，请求同意合作。";
    NSLog(@"请求合作按钮点击事件");
}

#pragma mark - SISSRequestCooperationViewDelegate
- (void)requestCooperationViewClickConfirmButtonWithCooperationReason:(NSString *)cooperationReason {
    
    NSLog(@"合作原因cooperationReason: %@",cooperationReason);
    
    NSDictionary *parameters = @{
                                 @"spId":[SISSUserAccount shared].spId,
                                 @"adcrId":self.houseCooperationModel.ID,
                                 @"cooperation_desc":cooperationReason
                                 };
    
    [kNetworkManager requestHouseCooperationRequestWithparameters:parameters success:^(id responseObject) {
        
        if ([responseObject[@"code"] integerValue] == 200) { // 请求合作成功
            
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                
                [SISSTools showSVSuccessTitle:@"请求合作成功" andTime:2 andColor:YES];
                EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithText:cooperationReason];
                
                EMMessage *message = [[EMMessage alloc] initWithConversationID:self.houseCooperationModel.imAccount from:[SISSUserAccount shared].imAccount to:self.houseCooperationModel.imAccount body:body ext:nil];
                [[EMClient sharedClient].chatManager sendMessage:message progress:nil completion:^(EMMessage *message, EMError *error) {
                    
                    
                }];
            }];
        }
    } failed:^(NSError *error) {
        
        NSLog(@"%@",error);
    }];

}




@end
